const express = require('express')
const UserModel = require('../../models/UserModel')
const router = express.Router()
const md5 = require('md5')

// 注册
router.get('/reg', (req, res) => {
   // 响应html内容
   res.render('auth/reg')
})

// 注册用户
router.post('/reg', async (req, res) => {
   // 获取请求体数据
   let result = await UserModel.create({ ...req.body, password: md5(req.body.password) })
   if (result) {
      res.render('success', { msg: '注册成功', url: '/login' })
   }
})

// 登录
router.get('/login', (req, res) => {
   // 响应html内容
   res.render('auth/login')
})

//登录操作
router.post('/login', async (req, res) => {
   // 获取用户名和密码
   let { username, password } = req.body
   // 查询数据库
   let result = await UserModel.findOne({ username: username, password: md5(password) })
   if (!result) {
      return res.send('账号或密码错误！')
   }
   // 写入session
   req.session.username = result.username
   req.session._id = result._id

   res.render('success', { msg: '登录成功！', url: '/account' })
})

// 退出登录
router.get('/logout', (req, res) => {
   // 销毁session
   req.session.destroy(() => {
      res.render('success', { msg: '退出成功', url: '/login' })
   })
})

module.exports = router